package com.dhh.sky.widget;

import java.util.Arrays;

import com.actionbarsherlock.app.SherlockDialogFragment;
import com.dhh.sky.R;
import com.dhh.sky.SDAApplication;
import com.dhh.sky.activity.BasicActivity;
import com.dhh.sky.activity.FileListActivity;
import com.dhh.sky.model.SkyDriveObject;
import com.dhh.sky.service.CopyOperationService;
import com.dhh.sky.service.MoveOperationService;
import com.dhh.sky.util.Config;
import com.dhh.sky.util.Constant;
import com.dhh.sky.util.FileManager;
import com.dhh.sky.util.OperationManager;
import com.microsoft.live.LiveAuthClient;
import com.microsoft.live.LiveAuthException;
import com.microsoft.live.LiveAuthListener;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveConnectSession;
import com.microsoft.live.LiveStatus;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.OnEditorActionListener;

public class FolderChooseDialog extends SherlockDialogFragment implements OnEditorActionListener {
	private String currentPath = Constant.SKYFRIVE_PATH_HOME;
	private String oPath;
	private FolderChooserAdapter adapter;
	private ListView listView;
	private LinearLayout loading;
	private Button okButton;
	private FileManager fm;
	private FileListActivity context;
	private Dialog dialog;
	private LinearLayout upButton;
	private OperationManager om;
	
	public interface FolderChooseDialogListener {
		void onFinishEditDialog(String inputText);
	}

	public FolderChooseDialog(FileListActivity context) {
		this.context = context;
		this.om = new OperationManager(context);
		this.fm = new FileManager(context);
	}

	public View onCreateViewdd(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		Bundle data = this.getArguments();
		final String[] items = data.getStringArray(Constant.PARAM_ITEM_NAME);
		oPath = data.getString(Constant.PARAM_PATH);
		final int action = data.getInt(Constant.PARAM_REQUEST);
		
		View view = inflater.inflate(R.layout.dialog_folder_choose, container);
		DisplayMetrics displaymetrics = new DisplayMetrics();
		this.getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		int height = displaymetrics.heightPixels;
		int width = displaymetrics.widthPixels;		
		view.findViewById(R.id.cli_list_layout).getLayoutParams().height = height*2/3;
		view.findViewById(R.id.list_empty).getLayoutParams().width = width*4/5;	
		okButton = (Button) view.findViewById(R.id.fc_ok);
		Button cancelButton = (Button) view.findViewById(R.id.fc_cancel);
		
		dialog = this.getDialog();
		loading = (LinearLayout) view.findViewById(R.id.td_loading);	
		loading.getLayoutParams().height = height*2/3;
		loading.getLayoutParams().width = width*4/5;
		
		if(Constant.REQ_OPERATION_COPY==action){
			dialog.setTitle(R.string.title_copy_to);
		}else if(Constant.REQ_OPERATION_MOVE==action){
			dialog.setTitle(R.string.label_move_to);
		}
		
		
		
		listView = (ListView) view.findViewById(R.id.listView1);	
		listView.getLayoutParams().width = width*4/5;	
		adapter = new FolderChooserAdapter(context);		
		listView.setAdapter(adapter);
		listView.setEmptyView(view.findViewById(R.id.list_empty));
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				SkyDriveObject file = adapter.getItem(position);
				if(file.isFolder()){
					currentPath = adapter.getItem(position).getId();
					adapter.setPath(currentPath);
					initData();
				}
			}
		});		
		
		upButton = (LinearLayout) view.findViewById(R.id.cli_button_up);
		upButton.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				SkyDriveObject file = fm.getFile(currentPath);
				if(file!=null){
					currentPath = file.getParentId();
				}else{
					currentPath = Constant.SKYFRIVE_PATH_HOME;
				}		
				initData();				
			}
		});
		
		
		cancelButton.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				getDialog().dismiss();
			}
		});
		
		
		okButton.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				if(Constant.REQ_OPERATION_COPY==action){
					om.addCopyOperation(items, currentPath);
					Intent intent = new Intent(context,CopyOperationService.class);
					context.startService(intent);
				}else if(Constant.REQ_OPERATION_MOVE==action){
					om.addMoveOperation(items, currentPath);
					Intent intent = new Intent(context,MoveOperationService.class);
					context.startService(intent);
				}
				context.onProgressStatus(true);
				dialog.dismiss();
			}
		});
		
		initData();
		
		return view;
	}
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState){
		final int action = Constant.REQ_OPERATION_COPY;
		LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.dialog_folder_choose, null);
		String title = "";
		if(Constant.REQ_OPERATION_COPY==action){
			title = getString(R.string.label_copy_to);
		}else if(Constant.REQ_OPERATION_MOVE==action){
			title = getString(R.string.label_move_to);
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(getSherlockActivity());
		builder.setView(view);
		
		
		listView = (ListView) view.findViewById(R.id.listView1);	
		//listView.getLayoutParams().width = width*4/5;	
		adapter = new FolderChooserAdapter(context);		
		listView.setAdapter(adapter);
		listView.setEmptyView(view.findViewById(R.id.list_empty));
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				SkyDriveObject file = adapter.getItem(position);
				if(file.isFolder()){
					currentPath = adapter.getItem(position).getId();
					adapter.setPath(currentPath);
					initData();
				}
			}
		});		
		
		upButton = (LinearLayout) view.findViewById(R.id.cli_button_up);
		upButton.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				SkyDriveObject file = fm.getFile(currentPath);
				if(file!=null){
					currentPath = file.getParentId();
				}else{
					currentPath = Constant.SKYFRIVE_PATH_HOME;
				}		
				initData();				
			}
		});
		
		initData();
		
		
		builder.setPositiveButton(R.string.label_ok,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            
                        }
                    }
                )
                .setNegativeButton(R.string.label_cancel,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            
                        }
                    }
                );
        
        return builder.create();
	}
	
	public void initData(){
		initUpButton();
		
		if(currentPath.equals(oPath) && okButton!=null){
			//okButton.setEnabled(false);
		}else{
			//okButton.setEnabled(true);
		}
		
		if(fm.needSync(currentPath)){
			refreshFolders();
		}else{
			listView.setVisibility(View.VISIBLE);
			//loading.setVisibility(View.GONE);
			adapter.setPath(currentPath);
			adapter.loadFiles();
			adapter.notifyDataSetChanged();
		}		
	}
	
	public void refreshFolders(){
		listView.setVisibility(View.GONE);
		loading.setVisibility(View.VISIBLE);
		
		new FileSyncTask().execute();
	}
	
	private void initUpButton(){
		if(Constant.SKYFRIVE_PATH_HOME.equals(currentPath)){
			upButton.setVisibility(View.GONE);
		}else{
			upButton.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		if (EditorInfo.IME_ACTION_DONE == actionId) {
			this.dismiss();
			return true;
		}
		return false;
	}
	
	public void doSync(final BasicActivity context,final String path){
		try {			
			final SDAApplication app = ((SDAApplication) context.getApplication());
			LiveConnectClient mClient = app.getConnectClient();
			
			if(mClient!=null){
				fm.syncFiles(mClient,path);				
			}else{
				final LiveAuthClient aClient = new LiveAuthClient(context,Config.CLIENT_ID);
				aClient.initialize(Arrays.asList(Config.SCOPES), new LiveAuthListener(){
		            @Override
		            public void onAuthError(LiveAuthException exception, Object userState) {
		            	dialog.dismiss();
		            	context.sendToast(context.getString(R.string.msg_error_network));
		            }

		            @Override
		            public void onAuthComplete(LiveStatus status,LiveConnectSession session,Object userState) {
		                if (status==LiveStatus.CONNECTED) {
		                	app.setAuthClient(aClient);
		                	app.setSession(session);
		                	LiveConnectClient conn = new LiveConnectClient(session);
		                    app.setConnectClient(conn);
		                    refreshFolders();
		                }else{
		                	dialog.dismiss();
			            	context.sendToast(context.getString(R.string.msg_error_connect));
		                }
		            }
		        });
			}			
		}catch(Exception e){
			Log.e(Constant.TAG, e.getMessage());
		}
	}
	
	public class FileSyncTask extends AsyncTask<Void, Void, Boolean>{
		boolean isInitCon = false;
		
		@Override
		protected Boolean doInBackground(Void... params) {
			if(((SDAApplication)context.getApplication()).getConnectClient()==null){
				isInitCon = true;
			}
			doSync(context, currentPath);
			return true;		
		}
		
		@Override
        protected void onPostExecute(final Boolean isLogin) {
			if(!isInitCon){
				refreshHandler.sendEmptyMessage(0);
			}
		}		
	}
	
	private Handler refreshHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {    
    		listView.setVisibility(View.VISIBLE);
    		loading.setVisibility(View.GONE);    		
    		adapter.setPath(currentPath);
    		adapter.loadFiles();
    		adapter.notifyDataSetChanged();
        }
    };
}
